<!-- eslint-disable vue/valid-attribute-name -->
<template>
  <el-card style="height: 80px">
    <el-form :inline="true" class="form">
      <el-form-item label="用户名:">
        <el-input placeholder="请你输入搜索用户名" v-model="keyword"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="default" @click="search">
          搜索
        </el-button>
        <el-button type="default" size="default" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0px">
    <el-button type="primary" size="default" @click="addUser">
      添加用户
    </el-button>
    <el-button
      type="danger"
      size="default"
      :disabled="selectIdArr.length ? false : true"
      @click="deleteSelectUser"
    >
      批量删除
    </el-button>
    <!-- table展示用户信息 -->
    <el-table
      style="margin: 10px 0px"
      border
      :data="userArr"
      @selection-change="selectChange"
    >
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column label="#" align="center" type="index"></el-table-column>
      <el-table-column label="ID" align="center" prop="id"></el-table-column>
      <el-table-column
        label="用户名字"
        align="center"
        prop="username"
        show-overflow-tooltip
      ></el-table-column>

      <el-table-column
        label="用户角色"
        align="center"
        prop="rolename"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        show-overflow-tooltip
        :formatter="createTimeformatter"
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        show-overflow-tooltip
        :formatter="updateTimeformatter"
      ></el-table-column>
      <el-table-column label="操作" width="300px" align="center">
        <template #="{ row }">
          <el-button
            type="primary"
            size="small"
            icon="User"
            @click="setRole(row)"
          >
            分配角色
          </el-button>
          <el-button
            type="warning"
            size="small"
            icon="User"
            @click="updateUser(row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            :title="`你确定要删除 ${row.username} 吗？`"
            @confirm="deleteUser(row.id)"
          >
            <template #reference>
              <el-button type="danger" size="small" icon="Delete">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[5, 7, 9, 11]"
      :background="true"
      @current-change="getHasUser"
      @size-change="handler"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
    />
  </el-card>
  <!-- 抽屉结构:完成添加新的用户账号|更新已有的账号信息 -->
  <el-drawer v-model="drawer">
    <!-- 头部标题 -->
    <template #header>
      <h4>{{ userParams.id ? '编辑用户' : '添加用户' }}</h4>
    </template>
    <template #default>
      <el-form :model="userParams" :rules="rules" ref="formRef">
        <el-form-item label="用户账号" prop="username">
          <el-input
            placeholder="请输入用户账号"
            v-model="userParams.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input
            placeholder="请输入用户密码"
            type="password"
            v-model="userParams.password"
          ></el-input>
        </el-form-item>
        <!-- 确认密码 -->
        <el-form-item label="确认密码" prop="checkPassword">
          <el-input
            placeholder="请输入确认密码"
            type="password"
            v-model="userParams.checkPassword"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-drawer>
  <!-- 抽屉结构:用户某一个已有的账号进行职位分配 -->
  <el-drawer v-model="drawer1">
    <template #header>
      <h4>分配角色(职位)</h4>
    </template>
    <template #default>
      <el-form>
        <el-form-item label="用户姓名">
          <el-input v-model="userParams.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="职位列表">
          <el-radio-group v-model="userRole">
            <el-radio
              v-for="item in allRole"
              :key="item.id"
              :label="item.id"
              border
              style="margin-bottom: 10px"
            >
              {{ item.rolename }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer1 = false">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref } from 'vue'
import type { Records, User } from '@/api/acl/user/type'
import {
  reqAllUser,
  reqAddOrUpdateUser,
  reqAllRole,
  reqSetUserRole,
  reqRemoveUser,
  reqSelectUser,
  reqCheckUser,
} from '@/api/acl/user'

import { ElMessage } from 'element-plus'
import useLayOutSettingStore from '@/store/modules/settings'

let pageNo = ref<number>(1)
let pageSize = ref<number>(5)
let total = ref<number>(0)

let userArr = ref<Records>([])
let drawer = ref<boolean>(false)
let drawer1 = ref<boolean>(false)
let allRole = ref()
let userRole = ref()

let userParams = reactive<User>({
  username: '',
  password: '',
  checkPassword: '',
})
let formRef = ref<any>()
// 存储批量删除的用户id
let selectIdArr = ref<User[]>([])
// 关键字
let keyword = ref<string>('')
// 获取模板setting仓库
let settingStore = useLayOutSettingStore()
onMounted(() => {
  getHasUser()
})
// 获取全部已有的用户信息
const getHasUser = async (pager = 1) => {
  // 收集当前页码
  pageNo.value = pager
  let result: any = await reqAllUser(
    pageNo.value,
    pageSize.value,
    keyword.value,
  )

  if (result.code == 200) {
    total.value = result.total
    userArr.value = result.data
  }
}

const handler = () => {
  getHasUser()
}
const formatDate = (isoString: any) => {
  try {
    const date = new Date(isoString)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const hours = date.getHours().toString().padStart(2, '0')
    const minutes = date.getMinutes().toString().padStart(2, '0')
    const seconds = date.getSeconds().toString().padStart(2, '0')

    // 构建格式化的日期字符串
    const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    return formattedDate
  } catch (error) {
    console.error('Invalid date format:', error)
    return null
  }
}
const createTimeformatter = (row: any) => {
  return formatDate(row.createTime)
}
const updateTimeformatter = (row: any) => {
  return formatDate(row.updateTime)
}
const addUser = () => {
  drawer.value = true
  // 清空数据
  Object.assign(userParams, {
    id: 0,
    username: '',
    password: '',
    checkPassword: '',
  })
  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate()
  })
}
// 更新用户信息
const updateUser = (row: User) => {
  // 抽屉显示
  drawer.value = true
  // 存储收集已有的账号信息
  Object.assign(userParams, row)
  // 清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate()
  })
}
const cancel = () => {
  drawer.value = false
}
const save = async () => {
  await formRef.value.validate()
  let result: any = await reqAddOrUpdateUser(userParams)
  // 添加或更新成功
  if (result.code == 200) {
    // 关闭抽屉
    drawer.value = false
    // 提示信息
    ElMessage({
      type: 'success',
      message: userParams.id ? '更新成功' : '添加成功',
    })
    // getHasUser(userParams.id ? pageNo.value : 1)
    // 刷新页面
    window.location.reload()
  } else {
    // 关闭抽屉
    drawer.value = false
    // 提示信息
    ElMessage({
      type: 'error',
      message: userParams.id ? '更新失败' : '添加失败',
    })
  }
}
// 表单校验
//校验用户名字回调函数
const validatorUsername = async (_rule: any, value: any, callBack: any) => {
  //用户名字|昵称,长度至少五位
  if (value.trim().length >= 5) {
    const result: any = await reqCheckUser(value)
    if (result.code == 200) {
      callBack(new Error('用户名已存在'))
    } else {
      callBack()
    }
  } else {
    callBack(new Error('用户名字至少五位'))
  }
}
//校验用户名字回调函数
const validatorName = (_rule: any, value: any, callBack: any) => {
  //用户名字|昵称,长度至少五位
  if (value.length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户昵称至少五位'))
  }
}
const validatorPassword = (_rule: any, value: any, callBack: any) => {
  //用户名字|昵称,长度至少五位
  if (value.length >= 6) {
    callBack()
  } else {
    callBack(new Error('用户密码至少六位'))
  }
}
const validatorCheckPassword = (_rule: any, value: any, callBack: any) => {
  //用户名字|昵称,长度至少五位
  if (value.length >= 6) {
    if (value == userParams.password) {
      callBack()
    } else {
      callBack(new Error('两次密码不一致'))
    }
  } else {
    callBack(new Error('用户密码至少六位'))
  }
}
//表单校验的规则对象
const rules = {
  //用户名字
  username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
  //用户昵称
  name: [{ required: true, trigger: 'blur', validator: validatorName }],
  //用户的密码
  password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
  //用户的密码
  checkPassword: [
    { required: true, trigger: 'change', validator: validatorCheckPassword },
  ],
}

//分配角色按钮的回调
const setRole = async (row: User) => {
  //
  Object.assign(userParams, row)
  //
  let result = await reqAllRole(userParams.id as number)
  if (result.code == 200) {
    // 获取所有的角色列表
    allRole.value = result.data.allRolesList
    // 存储已有的角色列表
    userRole.value = result.data.assignRoles
    // 显示抽屉
    drawer1.value = true
  }
}

// 确定按钮的点击事件
const confirmClick = async () => {
  // 收集参数
  let data = {
    userId: userParams.id as number,
    roleId: userRole.value as number,
  }
  // 分配用户的职位
  let result: any = await reqSetUserRole(data)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '分配职务成功',
    })
    // 关闭抽屉
    drawer1.value = false
    // 获取更新完毕的用户信息，更新完毕留在当前页
    getHasUser(pageNo.value)
  } else {
    ElMessage({
      type: 'error',
      message: '分配职务失败',
    })
    drawer1.value = false
    getHasUser(pageNo.value)
  }
}
// 删除某一个用户
const deleteUser = async (userId: number) => {
  let result: any = await reqRemoveUser(userId)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
    getHasUser(pageNo.value)
  }
}
// table复选框勾选触发事件
const selectChange = (value: any) => {
  selectIdArr.value = value
}
// 批量删除按钮回调
const deleteSelectUser = async () => {
  let idsList: any = selectIdArr.value.map((item) => {
    return item.id
  })
  // 请求
  let result: any = await reqSelectUser(idsList)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
    getHasUser(pageNo.value)
  }
}
// 搜索按钮回调
const search = () => {
  getHasUser()
  keyword.value = ''
}
// 重置按钮回调
const reset = () => {
  settingStore.refresh = !settingStore.refresh
}
</script>

<style lang="scss" scoped></style>
